import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/user_protocol_page.dart';
import 'package:flutter_learn_vi/src/page/login/LoginType.dart';
import 'package:flutter_learn_vi/src/utils/sp_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import '../login_model.dart';
import 'CustumOvalButton.dart';
import 'kuang_input_widget.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/11/22.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
/// 西瓜视频 https://www.ixigua.com/home/3662978423
/// 知乎 https://www.zhihu.com/people/zhao-long-90-89
///
///
/// 气泡背景的登录页面

void main() => runApp(
      MaterialApp(
        home: KuangDengLogin2Page(),
      ),
    );

class KuangDengLogin2Page extends StatefulWidget {
  final String userName;
  final String password;

  const KuangDengLogin2Page({Key key, this.userName, this.password})
      : super(key: key);

  @override
  _KuangDengLogin2PageState createState() => _KuangDengLogin2PageState();
}

class _KuangDengLogin2PageState extends State<KuangDengLogin2Page>
    with LoginModel {
  //RichText 富文本中使用的手势识别
  TapGestureRecognizer _gestureRecognizer;
  TapGestureRecognizer _gestureRecognizer2;
  LoginType _loginType = LoginType.idCard;

  bool _isSendLoading = false;

  @override
  void initState() {
    super.initState();
    String loginType = SPUtil.getString("loginType");
    if (loginType != null && loginType != "") {
      if (loginType == LoginType.defalut.toString()) {
        _loginType = LoginType.defalut;
      } else if (loginType == LoginType.mobile.toString()) {
        _loginType = LoginType.mobile;
      } else if (loginType == LoginType.staff.toString()) {
        _loginType = LoginType.staff;
      } else if (loginType == LoginType.idCard.toString()) {
        _loginType = LoginType.idCard;
      }
      //_loginType = LoginType.defalut;
      _gestureRecognizer = TapGestureRecognizer();
      _gestureRecognizer2 = TapGestureRecognizer();

      String preLoginUserName = SPUtil.getString("preLoginUserName");
      String preLoginPassword = SPUtil.getString("preLoginPassword");
      if (preLoginUserName != null && preLoginUserName != "") {
        _userNameController.text = preLoginUserName;
        _passwordController.text = preLoginPassword;
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (_passwordStreamController != null) {
      _passwordStreamController.close();
    }
    hidenKeyBoard();
    if (_gestureRecognizer != null) {
      _gestureRecognizer.dispose();
      _gestureRecognizer2.dispose();
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    return Scaffold(
      //背景颜色
      backgroundColor: Color(0xffffffff),
      resizeToAvoidBottomInset: false,
      //内容主体
      body: GestureDetector(
        onTap: () {
          hidenKeyBoard();
        },
        child: Container(
          //填充屏幕空间
          width: double.infinity,
          height: double.infinity,
          child: buildColumn(),
        ),
      ),
    );
  }

  //文本输入框控制器
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  //焦点控制器
  FocusNode _userNameFocusNode = new FocusNode();
  FocusNode _passwordFocusNode = new FocusNode();

  //是否选中用户协议
  bool _isProtocol = false;
  bool _passwordIvi = true;
  StreamController<bool> _passwordStreamController = new StreamController();

  Column buildColumn() {
    return Column(
      children: [
        SizedBox(
          height: 104,
        ),
        Container(
          padding: EdgeInsets.only(left: 40, right: 40),
          child: Row(
            children: [
              Image.asset(
                "assets/images/2.0x/app_icon_yuxi.png",
                width: 46,
                height: 46,
              ),
              SizedBox(
                width: 12,
              ),
              Text(
                "一个职工素质和管理效率\n双重提升的信息平台",
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),

        SizedBox(
          height: 30,
        ),

        SizedBox(
          height: 20,
        ),
        Container(
          height: 54,
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 40, right: 40),
          child: KuangDengInputWidget(
            labelText: buildLoginUserNameText(),
            hintText: '请输入${buildLoginUserNameText()}',
            focusNode: _userNameFocusNode,
            controller: _userNameController,
            obscureText: false,
            prefixIconData: Icons.mail_outline,
            submit: (String value) {
              //焦点切换
              _userNameFocusNode.unfocus();
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
          ),
        ),
        SizedBox(
          height: 24,
        ),
        Container(
          height: 54,
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 40, right: 40),
          child: StreamBuilder(
            initialData: true,
            stream: _passwordStreamController.stream,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              return KuangDengInputWidget(
                labelText: "密码",
                hintText: '请输入密码',
                controller: _passwordController,
                focusNode: _passwordFocusNode,
                obscureText: snapshot.data,
                prefixIconData: Icons.lock_outline,
                suffixIconData:
                    snapshot.data ? Icons.visibility : Icons.visibility_off,
                submit: (String value) {
                  _submitLoginFunction();
                },
                onTap: () {
                  _passwordIvi = !_passwordIvi;
                  _passwordStreamController.add(_passwordIvi);
                },
              );
            },
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 20),
          padding: EdgeInsets.only(left: 30, right: 40),
          child: Row(
            children: [
              Checkbox(
                value: _isProtocol,
                checkColor: Colors.blue,
                onChanged: (bool value) {
                  setState(() {
                    _isProtocol = value;
                  });
                },
              ),
              InkWell(
                onTap: () {
                  showUserProtocolPage(
                      context: context, isOneButton: true, rightText: "同意");
                },
                child: Text(
                  '登录即代表同意隐私协议',
                  style: TextStyle(
                    color: _isProtocol ? Colors.blue : Colors.blueGrey,
                  ),
                ),
              ),
            ],
          ),
        ),
        //登录按钮
        buildLoginButton(),

        SizedBox(height: 22),
        //隐私协议
        // buildRichText(),
        Container(
          padding: EdgeInsets.only(bottom: 22),
          child: Text(
            'APP备案号:京ICP备18060046号-5A',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ),
        //填充空白
        Expanded(
          child: Container(
            padding: EdgeInsets.only(bottom: 34),
            //水平方向排开
            child: Offstage(
              offstage: true,
              child: buildRow(),
            ),
          ),
        )
      ],
    );
  }

  Row buildRow() {
    return Row(
      //水平方向居中
      mainAxisAlignment: MainAxisAlignment.center,
      //竖直方向底部对齐
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CustumOvalButton(
              iconData: Icons.phone_iphone,
              color:
                  _loginType == LoginType.mobile ? Colors.blue : Colors.black54,
              clickCallBack: () {
                ToastUtils.showToast("已切换为手机号登录");
                _loginType = LoginType.mobile;
                setState(() {});
              },
            ),
            Text(
              "手机号",
              style: TextStyle(
                  fontSize: 10,
                  color: _loginType == LoginType.mobile
                      ? Colors.blue
                      : Colors.black54),
            )
          ],
        ),
        SizedBox(
          width: 20,
        ),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CustumOvalButton(
              iconData: Icons.laptop,
              color: _loginType == LoginType.defalut
                  ? Colors.blue
                  : Colors.black54,
              clickCallBack: () {
                ToastUtils.showToast("已切换为账号登录");
                _loginType = LoginType.defalut;
                setState(() {});
              },
            ),
            Text(
              "账号",
              style: TextStyle(
                  fontSize: 10,
                  color: _loginType == LoginType.defalut
                      ? Colors.blue
                      : Colors.black54),
            )
          ],
        ),
        SizedBox(
          width: 20,
        ),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CustumOvalButton(
              iconData: Icons.list,
              clickCallBack: () {
                showBottomSheet();
              },
            ),
            Text(
              "更多登录",
              style: TextStyle(fontSize: 10, color: Colors.black54),
            )
          ],
        ),
      ],
    );
  }

  Widget buildLoginButton() {
    return Container(
      margin: EdgeInsets.only(top: 64),
      width: 220,
      height: 44,
      child: OutlinedButton(
        onPressed: () {
          print("点击了手机号登录");
          _submitLoginFunction();
        },
        child: _isSendLoading ? LoadingWidget() : Text("登 录"),
      ),
    );
  }

  //封装方法
  RichText buildRichText() {
    return RichText(
      text: TextSpan(
          text: "登录同意",
          style: TextStyle(color: Colors.grey),
          children: [
            TextSpan(
                text: "用户协议",
                style: TextStyle(
                  color: Colors.orange,
                ),
                //点击事件
                recognizer: _gestureRecognizer
                  ..onTap = () {
                    print("用户协议点击");
                  }),
            TextSpan(
              text: "和",
              style: TextStyle(color: Colors.grey),
            ),
            TextSpan(
                text: "隐私协议",
                style: TextStyle(
                  color: Colors.orange,
                ),
                //点击事件
                recognizer: _gestureRecognizer2
                  ..onTap = () {
                    print("隐私协议点击");
                  }),
          ]),
    );
  }

  ///登录
  void _submitLoginFunction() async {
    //隐藏键盘
    hidenKeyBoard();
    if (_isSendLoading) {
      return;
    }
    //获取用户输入的内容
    String userName = _userNameController.text.trim();
    String password = _passwordController.text.trim();

    // userName = "140581197311234831";
    // password = "123456";

    //教师
    // userName = "140502199306012998";
    // password = "123456";
    // userName = "140581197311204819";
    // password = "123456";

    //学员
    // userName = "140581197002154811";
    // password = "123456";
    // userName = "140581199204013610";
    // password = "123456";

    // 测试班主任01
    // userName = "140523197003107810";
    // password = "123456";

    // 测试教师
    // userName = "140581199204013602";
    // password = "123456";

    //线上
    // userName = "14058119891025365X";
    // password = "123456";

    if (userName.length == 0) {
      ToastUtils.showToast("请输入${buildLoginUserNameText()}");
      return;
    }
    if (password.length == 0) {
      ToastUtils.showToast("请输入密码");
      return;
    }

    SPUtil.save("preLoginUserName", userName);
    SPUtil.save("preLoginPassword", password);

    if (!_isProtocol) {
      ToastUtils.showToast("请同意用户协议");
      return;
    }
    SPUtil.save("loginType", _loginType.toString());
    setState(() {
      _isSendLoading = true;
    });
    //校验
    bool result = await submitV3(userName, password, buildLoginType(), context);

    setState(() {
      _isSendLoading = false;
    });
  }

  void hidenKeyBoard() {
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    _passwordFocusNode.unfocus();
    _userNameFocusNode.unfocus();
  }

  //显示底部弹框的功能
  void showBottomSheet() {
    //用于在底部打开弹框的效果
    showModalBottomSheet(
        builder: (BuildContext context) {
          //构建弹框中的内容
          return buildBottomSheetWidget(context);
        },
        context: context);
  }

  Widget buildBottomSheetWidget(BuildContext context) {
    //弹框中内容  310 的调试
    return Container(
      height: 310,
      child: Column(
        children: [
          buildItem("手机号码登录", LoginType.mobile, onTap: () {
            setState(() {
              _loginType = LoginType.mobile;
            });
          }),
          //分割线
          Divider(),

          buildItem("员工号登录", LoginType.staff, onTap: () {
            setState(() {
              _loginType = LoginType.staff;
            });
          }),

          //分割线
          Divider(),
          buildItem("身份证号登录", LoginType.idCard, onTap: () {
            setState(() {
              _loginType = LoginType.idCard;
            });
          }),
          //分割线
          Divider(),
          buildItem("账号密码登录", LoginType.defalut, onTap: () {
            setState(() {
              _loginType = LoginType.defalut;
            });
          }),

          Container(
            color: Colors.grey[300],
            height: 8,
          ),

          //取消按钮
          //添加个点击事件
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              child: Text("取消"),
              height: 44,
              alignment: Alignment.center,
            ),
          )
        ],
      ),
    );
  }

  Widget buildItem(String title, LoginType loginType, {Function onTap}) {
    //添加点击事件

    return InkWell(
      //点击回调
      onTap: () {
        //关闭弹框
        Navigator.of(context).pop();
        //外部回调
        if (onTap != null) {
          onTap();
        }
      },
      child: Container(
        height: 40,
        //左右排开的线性布局
        child: Row(
          //所有的子Widget 水平方向居中
          mainAxisAlignment: MainAxisAlignment.center,
          //所有的子Widget 竖直方向居中
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 10,
            ),
            Text(title)
          ],
        ),
      ),
    );
  }

  buildLoginUserNameText() {
    String name = "手机号";
    switch (_loginType) {
      case LoginType.defalut:
        name = "账号";
        break;
      case LoginType.mobile:
        name = "手机号";
        break;
      case LoginType.staff:
        name = "员工号";
        break;
      case LoginType.idCard:
        name = "身份证号";
        break;
    }
    return name;
  }

  ///[loginType]
  /// 1 手机号
  /// 2 员工号
  /// 3 身份证号
  /// 4 账号
  int buildLoginType() {
    int loginType = 1;
    switch (_loginType) {
      case LoginType.defalut:
        loginType = 4;
        break;
      case LoginType.mobile:
        loginType = 1;
        break;
      case LoginType.staff:
        loginType = 2;
        break;
      case LoginType.idCard:
        loginType = 3;
        break;
    }
    return loginType;
  }
}
